package com.hx.vending.resolvers;


import com.hx.vending.annotation.CurrentFieldId;
import com.hx.vending.annotation.CurrentUserId;
import com.hx.vending.bean.config.Constants;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * @Description: 增加方法注入，将含有CurrentUser注解的方法参数注入当前userId
 * @See: com.hx.vending.resolvers.CurrentFieldIdMethodArgumentResolver
 */
@Component
public class CurrentFieldIdMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (methodParameter.getParameterType().isAssignableFrom(Integer[].class) &&
                methodParameter.hasParameterAnnotation(CurrentFieldId.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Object FieldId =  nativeWebRequest.getAttribute(Constants.CURRENT_FIELD_ID, RequestAttributes.SCOPE_REQUEST);
        if (FieldId.getClass().isArray()){
            Integer[] integers = (Integer[])FieldId;
            if (integers.length != 0) {
                return integers;
            }else{
                Integer[] integer = new Integer[1];
                integer[0] = 0;
                return integer;
            }
        }
        throw new MissingServletRequestPartException(Constants.CURRENT_FIELD_ID);
    }
}
